package com.seeyon.apps.kk.manager;

import java.util.Hashtable;

import javax.naming.Context;
import javax.naming.NamingException;
import javax.naming.ldap.InitialLdapContext;
import javax.naming.ldap.LdapContext;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.seeyon.kk.utils.ValueUtils;

public class AdLoginManager {
	private static final Log log = LogFactory.getLog(AdLoginManager.class);
	private String ldapurl;
	private String ldapSuffix;
	
	public String getLdapurl() {
		return ldapurl;
	}

	public void setLdapurl(String ldapurl) {
		this.ldapurl = ldapurl;
	}

	public String getLdapSuffix() {
		return ldapSuffix;
	}

	public void setLdapSuffix(String ldapSuffix) {
		this.ldapSuffix = ldapSuffix;
	}

	public boolean getIsLdapEnabled(){
		return ValueUtils.getConfig().getBooleanValue("kk.LdapEnabled");
	}
	
	
	public   boolean adLogin(String username, String password) {	 
		try {
			Hashtable<String, String> env = new Hashtable<String, String>();
			// 用户名称，cn,ou,dc 分别：用户，组，域
			env.put(Context.SECURITY_PRINCIPAL, username+ldapSuffix);
			// 用户密码 cn 的密码
			env.put(Context.SECURITY_CREDENTIALS, password);
			// url 格式：协议://ip:端口/组,域 ,直接连接到域或者组上面
			env.put(Context.PROVIDER_URL, this.ldapurl);
			// LDAP 工厂
			env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
			// 验证的类型 "none", "simple", "strong"
			env.put(Context.SECURITY_AUTHENTICATION, "simple");
			LdapContext ldapContext = new InitialLdapContext(env, null);
			log.info("kk:ldapContext:" + ldapContext);
			log.info("kk:用户" + username + "登录验证成功");
			return true;

		} catch (NamingException e) {
			log.info("kk:用户" + username + "登录验证失败");
			log.info("kk:错误信息：" + e.getExplanation());
			return false;
		}
	}
}
